package com.tanhua.server.service;


import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendVoice;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendVoiceApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 桃花传音逻辑处理层
 */
@Service
@Slf4j
public class VoiceService {

    @Reference
    private VoiceApi voiceApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private RecommendVoiceApi recommendVoiceApi;


    //注入客户端对象 进行文件上传 下载
    @Autowired
    private FastFileStorageClient client;
    //文件服务器地址对象
    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 桃花传音-接收语音
     */
    public VoiceVo peachblossomReceive() {
        Integer valueLong;
        VoiceVo voiceVo = null;
        //1.验证用户是否登录获取登录的用户id
        Long userId = UserHolder.getUserId();
        //2.根据用户id查询redis value的数值是否大于3
        String key = "peachblossomReceive" + userId;
        String value = redisTemplate.opsForValue().get(key);

        //3.如果大于3返回 次数限制
        if (StringUtils.isNotEmpty(value)) {
            if (Integer.valueOf(value) > 3) {
               throw  new TanHuaException("次数受限");
            }
        }
        //4.如果为空或者小于3 从推荐表中查询一条动态保证不重复
        RecommendVoice recommendVoice = recommendVoiceApi.queryMessage(userId);

        if (recommendVoice!=null) {
            //5.redis中用户id对应的值加1  存入查询动态的用户id到redis中
            valueLong = (value == null) ? 1 : (Integer.valueOf(value) + 1);

            redisTemplate.opsForValue().set(key, valueLong.toString());

            //6.封装数据返回
           voiceVo = new VoiceVo();

            //6.1 查询用户信息
            UserInfo userInfo = userInfoApi.queryUserInfo(recommendVoice.getUserId());

            //6.2 根据语言动态id 查询发布的语言动态信息表
            Voice voice = voiceApi.queryById(recommendVoice.getId());

            if (userInfo != null && voice != null) {
                BeanUtils.copyProperties(userInfo, voiceVo);
                BeanUtils.copyProperties(voice, voiceVo);

                BeanUtils.copyProperties(voice, voiceVo);
                voiceVo.setId(userInfo.getId().intValue());//用户id
                voiceVo.setAge(userInfo.getAge().intValue());//年龄

                int num = 4 - Integer.valueOf(redisTemplate.opsForValue().get(key));
                voiceVo.setRemainingTimes(num);
            }
        }else {
            throw  new TanHuaException("当前无最新的语音动态推荐信息");
        }
        //7.返回数据
        return voiceVo;
    }

    /**
     * 桃花传音: 发送语音
     *
     * @param soundFile
     */
    public void save(MultipartFile soundFile) {
        try {
            //1. 验证用户是否登录获取登陆的用户id
            Long userId = UserHolder.getUserId();
            //2. 接收文件存入fastdfs返回存储的路径
            //根据key获得发送语音的次数
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String key = today + "_voiceSent_" + userId;
            //获取记录

            String countStr = redisTemplate.opsForValue().get(key);
            Integer count = 0;
            if (countStr != null) {
                count = Integer.parseInt(countStr);
            } else {
                count = 0;
            }
            log.debug("-------次数--{}-------", count);
            if (count == 3) {
                throw new TanHuaException("今日次数已到达上限");
            }
            //调用方法,上传语音
            String videoUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            if (!StringUtils.isEmpty(videoUrl)) {
                //3. 插入信息到语音发表
                Voice voice = new Voice();
                voice.setVoiceUrl(videoUrl);
                voice.setUserId(userId);
                voice.setCreated(System.currentTimeMillis());
                voiceApi.add(voice);
            }
            count++;
            //将记录存到缓存中
            redisTemplate.opsForValue().set(key, count.toString(), 1, TimeUnit.DAYS);

        } catch (IOException e) {
            throw new TanHuaException(ErrorResult.error());
        }
    }
}
